<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 引包 -->
    <script src="../js/vue.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        table,
        tr,
        td {
            border: 1px solid red;
            border-collapse: collapse;
        }

        td {
            width: 150px;
            height: 50px;
            text-align: center;
            line-height: 50px;
        }
    </style>
</head>

<body>
    <!-- 容器|模板 -->
    <div id="app">
        <table>
            <tr v-for="(item,index) in cart" :key="item.id">
                <td>{{item.title}}</td>
                <td>{{item.price}}</td>
                <td>
                    <button @click="minus(item)">-</button>
                    {{item.count}}
                    <button @click="add(item)">+</button>
                </td>
                <td>{{item.price * item.count}}</td>
            </tr>
        </table>
        <h1>您需要支付总额:{{total}}</h1>
    </div>
</body>

</html>
<script>
    //关联VM
    const VM = new Vue({
        el: '#app',
        data: {
            cart: [
                { id: 1, title: '小米1', price: 3999, count: 1 },
                { id: 2, title: '小米2', price: 4999, count: 1 },
                { id: 3, title: '小米3', price: 5999, count: 1 },
                { id: 4, title: '小米4', price: 6999, count: 1 }
            ]
        },
        methods: {
            add(item) {
                item.count += 1
            },
            minus(item) {
                if (item.count > 1) {
                    item.count -= 1
                }
            }
        },
        computed: {
            total() {
                //   方法一
                // let sum = 0;
                // for (var i = 0; i < this.cart.length; i++){
                //     sum += this.cart[i].price * this.cart[i].count
                // };
                // return sum

                // 方法二 
                // let sum = 0;
                // this.cart.forEach(item => {
                //     sum += item.price * item.count
                // });
                // return sum

                // 方法三
            return this.cart.reduce((prev,next)=>prev += next.price * next.count,0);
            }
        }
    })
</script>